package com.ffcs.test.sentinel;

import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 天真热
 * @create 2024-01-25 19:48
 * 线程流控
 * sentinel流控可以再客户端可视化界面实现，这里主要是为了实现代码流控
 * https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8
 * @desc
 **/
@RestController
@RequestMapping("/sentinel")
public class SentinelController_degrade {
    public final static String RESOURCE_NAME = "sentinel/degrade";


//    /**
//     * 流控规则
//     */
//    @PostConstruct
//    public void initDegradeRule() {
//        /*降级规则′异常*/
//        List<DegradeRule> degradeRules = new ArrayList();
//        DegradeRule degradeRule = new DegradeRule();
//        degradeRule.setResource(RESOURCE_NAME);
//        //设置规则侧率:异常数
//        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
//
//        //=============一分钟内:执行了2次出现了2次异常就会触发===================
//        //触发熔断异常数:2
//        degradeRule.setCount(2);
//        //触发熔断最小请求数:2
//        degradeRule.setMinRequestAmount(2);
//        //统计时长,单位ms1
//        degradeRule.setStatIntervalMs(60 * 1000);
//
//        degradeRule.setTimeWindow(10);
//        degradeRules.add(degradeRule);
//        DegradeRuleManager.loadRules(degradeRules);
//    }


    /**
     * 通过注解实现熔断
     */
    @RequestMapping("/degrade")
    @SentinelResource(value = RESOURCE_NAME, entryType = EntryType.IN, blockHandler = "blockHandlerMethod")
    public String degrade() throws InterruptedException {
        int x = 1 / 0;
        return "111";
    }

    /**
     * 流控方法
     *
     * @return
     */
    public String blockHandlerMethod(BlockException blockException)  {
        return "触发熔断降级";
    }


}
